<?php
/**
 * Created by PhpStorm.
 * User: huangangui
 * Date: 2017/12/15
 * Time: 上午2:01
 */

namespace App\Service;


use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;

class RoleService
{
    public $repository, $rolePermissionService;

    public function __construct(Role $repository, RolePermissionService $rolePermissionService)
    {
        $this->repository = $repository;
        $this->rolePermissionService = $rolePermissionService;
    }

    /**
     * @author huangangui
     * @explain 设置角色权限
     * @param $permissionArr
     * @param $roleId
     */
    public function setPermission($permissionArr, $roleId){
        //拉取存在数据库中的数据
        $dbArr = $this->rolePermissionService->repository->where('role_id', $roleId)->get()->toArray();
        $dbArr = array_column($dbArr, 'permission_id');

        //不需要处理的数据(求数据库中与提交的数据的交集）
        $sameArr = array_intersect($dbArr, $permissionArr);

        //该删除的数据
        $delPermissionArr = array_diff($dbArr, $sameArr);

        //该添加的数据
        $addPermissionArr = array_diff($permissionArr, $sameArr);

        DB::transaction(function () use ($delPermissionArr, $addPermissionArr, $roleId){
            $addArr = [];

            if (!empty($delPermissionArr)){
                $res = $this->rolePermissionService->repository->whereIn('permission_id', $delPermissionArr)->where('role_id', $roleId)->delete();
                if ($res < 0){
                    throw new \Exception(__METHOD__.'delete:role_permissions failed');
                }
            }

            if (!empty($addPermissionArr)){

                foreach ($addPermissionArr as $key => $value){
                    $addArr[$key]['role_id'] = $roleId;
                    $addArr[$key]['permission_id'] = $value;
                }

                $res = DB::table('role_permissions')->insert($addArr);

                if ($res < 0){
                    throw new \Exception(__METHOD__.'create:role_permissions failed');
                }
            }

        });
    }

}